/* eslint-disable no-debugger */
/* eslint-disable @typescript-eslint/no-use-before-define */
import CustomerTable from "@/components/CustomerTable";
import DictTag from "@/components/DictTag";
import { getDict } from "@/services/api/module/system/dict";
import { authRole, getUserRolePage } from "@/services/api/module/system/role";
import { DownOutlined, ExclamationCircleFilled } from "@ant-design/icons";
import { ActionType, ProColumns, ProFormInstance } from "@ant-design/pro-components";
import { Button, Dropdown, FormInstance, MenuProps, Modal, Popconfirm, Space, Typography, message } from "antd";
import React, { useEffect, useRef, useState } from "react";

export type FormValueType = any & Partial<API.Setting.DeptVo>;

const { confirm } = Modal;
export type AuthRoleFormProps = {
	onCancel: (flag?: boolean, formVals?: FormValueType) => void;
	open: boolean;
	userId: number | undefined;
	roleIds: number[];
};

const AuthRoleForm: React.FC<AuthRoleFormProps> = props => {
	const { roleIds, onCancel, open, userId } = props;
	const formRef = useRef<ProFormInstance>();
	const formTableRef = useRef<FormInstance>();
	const [selectedRows, setSelectedRows] = useState<any>([]);
	const [bindOptions, setBindOption] = useState<any>([]);

	useEffect(() => {
		formRef?.current?.resetFields();
		formRef?.current?.setFieldValue("roleIds", roleIds);
	}, []);

	useEffect(() => {
		getDict("sys_auth_status").then(data => {
			setBindOption(data);
		});
	}, []);

	const handleCancel = () => {
		onCancel();
	};

	const actionRef = useRef<ActionType>();
	// 授权提示
	const showAuthConfirm = (ids: Array<number>, names: Array<string>) => {
		confirm({
			title: "警告",
			icon: <ExclamationCircleFilled />,
			content: `确认授权用户这些：${names} 的角色吗?`,
			onOk() {
				return handleAuth(ids);
			},
			onCancel() {}
		});
	};
	// 授权角色
	const handleAuth = async (ids: number | Array<number> | string) => {
		// const roleIds = typeof ids === 'number' ? [ids] : ids;
		return new Promise((reslove, reject) => {
			authRole({ userId: userId, roleIds: Array.isArray(ids) ? ids : [ids] })
				.then((res: any) => {
					message.success(res.msg);
					if (actionRef.current) {
						actionRef.current.reload();
					}
					reslove(true);
				})
				.catch(() => {
					reject(true);
				});
		});
	};

	const handleUnAuth = async (ids: number | Array<number>) => {
		const roleIds = typeof ids === "number" ? [ids] : ids;
		return new Promise((reslove, reject) => {
			authRole({ userId: userId, roleIds: roleIds })
				.then((res: any) => {
					message.success(res.msg);
					if (actionRef.current) {
						actionRef.current.reload();
					}
					reslove(true);
				})
				.catch(() => {
					reject(true);
				});
		});
	};

	const columns: ProColumns<API.Setting.UserRoleVo>[] = [
		{
			title: "角色名称",
			dataIndex: "roleName",
			valueType: "text"
		},
		{
			title: "角色编码",
			dataIndex: "roleKey",
			valueType: "text"
		},
		{
			title: "绑定状态",
			dataIndex: "status",
			valueType: "select",
			sorter: (e, e1) => {
				return Number(e?.status) - Number(e1?.status);
			},
			valueEnum: bindOptions,
			render: (_: any, record: any) => {
				return <DictTag enums={bindOptions} type="tag" value={record?.status} />;
			}
		},
		{
			title: "操作",
			dataIndex: "option",
			valueType: "option",
			render: (_: any, record: any) => {
				return (
					<>
						{/* @ts-ignore */}
						{record?.roleKey !== "superAdmin" && (
							<Space size={2}>
								{record?.status === "1" ? (
									<Popconfirm
										placement="bottomRight"
										title="提示"
										description={`确认授权用户这个: "${record.roleName}"角色吗？`}
										key="edit"
										onConfirm={async () => handleAuth(record?.id)}
										okText="确认"
										cancelText="取消"
									>
										<Typography.Link key="bind">授权</Typography.Link>
									</Popconfirm>
								) : (
									<Popconfirm
										placement="bottomRight"
										title="提示"
										description={`确认取消授权用户这个: "${record.roleName}"角色吗？`}
										key="edit"
										onConfirm={async () => handleUnAuth(record?.id)}
										okText="确认"
										cancelText="取消"
									>
										<Typography.Link type="danger" key="bind">
											取消授权
										</Typography.Link>
									</Popconfirm>
								)}
							</Space>
						)}
					</>
				);
			}
		}
	];

	const items: MenuProps["items"] = [
		{
			key: "bind",
			label: (
				<a
					type="bind"
					key="export"
					onClick={async () => {
						if (selectedRows.length <= 0) {
							message.warning("请选择一条或多条数据");
							return;
						}
						showAuthConfirm(
							Array.from(selectedRows, ({ id }) => id),
							Array.from(selectedRows, ({ roleName }) => roleName)
						);
					}}
				>
					<Space>批量绑定</Space>
				</a>
			)
		},
		{
			key: "cancel",
			label: (
				<a type="cancel" target="_blank" rel="noopener noreferrer" onClick={() => {}}>
					批量取消
				</a>
			),
			danger: true
		}
	];
	return (
		<>
			<Modal title="角色授权" maskClosable={false} footer={null} open={open} width={"70%"} centered onCancel={handleCancel}>
				<CustomerTable<API.Setting.UserRoleVo>
					ghost
					// cardProps={{
					//   bodyStyle: {
					//     height: 'calc(100vh - 300px)',
					//   },
					// }}
					actionRef={actionRef}
					pagination={{
						defaultPageSize: 10,
						showQuickJumper: true,
						showSizeChanger: true
					}}
					tableAlertRender={false}
					headerTitle="角色列表"
					search={{
						filterType: "light"
					}}
					formRef={formTableRef}
					rowKey="id"
					style={{ width: "100%" }}
					key="bindRoleList"
					rowSelection={{
						onChange: (_, selectedRows) => {
							setSelectedRows(selectedRows);
						},
						getCheckboxProps: (record: any) => ({
							disabled: record?.id === 1, // Column configuration not to be checked
							name: record.id
						})
					}}
					request={async params => {
						return await getUserRolePage({ ...params, userId: userId }).then((res: any) => {
							return res;
						});
					}}
					columns={columns}
					// @ts-ignore
					toolBarRender={() => {
						return (
							<>
								<Dropdown placement="bottom" trigger={["click"]} menu={{ items }}>
									<Button key="bindOper">
										绑定操作
										<DownOutlined />
									</Button>
								</Dropdown>
							</>
						);
					}}
				/>
			</Modal>
		</>
	);
};

export default AuthRoleForm;
